<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>
<body>
  <script>
    /**
   * @see https://leetcode-cn.com/problems/consecutive-numbers-sum/
   * 给定一个正整数 N，试求有多少组连续正整数满足所有数字之和为 N?
   * @param {number} N
   * @return {number}
   */
  var consecutiveNumbersSum = function(N) {
    let countedCache = {};
    let resultMap = {};
    // 递归计算这个整数所有相加的组合
    function sum(d) {
      // 缓存已经计算过的数据，减少计算次数
      if(countedCache[d]) {
        return countedCache[d];
      }
      let start = Math.floor(d/2);
      let group = [];
      while(start >=1) {
        let dif = d - start;
        let result
        // 已经有一个递增序列了
        if(Math.abs(dif - start) === 1) {
          result = [start, dif];
          if(!resultMap[result.toString()]) {
            group.push(result);
            resultMap[result.toString()] = true;
          }
        }
        if(dif === start) {
          start--;
          continue;
        }
        if(dif > 2) {
          result = sum(dif);
          countedCache[dif] = result;
          if(!result.length) {
            console.log('没有递增序列', dif)
          } else {
            // 存在递增序列，则用start值与结果进行比较，判断是否递增
            result = result[0].concat(start);
            if(isIncrease(result)) {
              if(!resultMap[result.toString()]) {
                group.push(result);
                resultMap[result.toString()] = true;
              }
            }
          }
        }   
        start--;  
      }
      return group;
    } 
    let result = sum(N);
    // 去重复
    console.log(result)
  };

  function isIncrease(arr) {
    arr.sort();
    let is = true;
    arr.reduce((prev, next,i, array) => {
      if(next - prev === 1) {
        return next;
      } else {
        is = false;
        array.splice(1)
        return next;
      }
    })
    return is;
  }
  consecutiveNumbersSum(85);
  </script>
</body>
</html>